package ru.arriah.servicedesk.web.executor;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.bean.MessageBean;
import ru.arriah.common.web.UIController;
import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.bean.IntWrapper;
import ru.arriah.servicedesk.bean.TaskBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.IllegalLanguageException;
import ru.arriah.servicedesk.web.commonaction.exception.LoginException;

public class ExecutorUI extends UIController {
  protected EmployeeManagerLocalHome employeeManagerHome;
  protected RequestManagerLocalHome requestManagerHome;
  
  public ExecutorUI() {
      super();
   }
   
  
   public void init(ServletConfig config) throws ServletException {
      super.init(config);
      try {        
         employeeManagerHome =
            Utils.getEmployeeManagerHomeInterface();
         
         requestManagerHome = 
            Utils.getRequestManagerHomeInterface();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   
   protected void prologue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {

      request.getSession().setAttribute("alias", "executorui");
      
      Object userId = Utils.getUserId(request);

      if (
         userId == null && !actionMapping.getActionName().equals("login")
      ) {         
         throw new LoginException("ErrorMessage.relogin");
      }

      String uri = request.getRequestURI();
      String query = request.getQueryString();     

      if (query != null) {
         uri += "?" + query;
      }

      String uriEncoded = URLEncoder.encode(uri, "UTF-8");
      request.setAttribute("uri", uri);
      request.setAttribute("uriEncoded", uriEncoded);     
      
      /* messages list */              
      request.setAttribute(
         "messagesList", 
         new ArrayList<MessageBean>()
      );
   }
   
   
   private void displayUserName(HttpServletRequest request) {
      try {
         int userId = Utils.getUserId(request);
         
         EmployeeManagerLocalObject employeeManager = 
            employeeManagerHome.create();
         
         EmployeeBean employeeBean = 
            employeeManager.selectEmployee(userId);
                  
         request.setAttribute("userName", employeeBean.getFormName());
         
         employeeManager.remove();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }     
   }
   
   
   private void displaySideBarList(HttpServletRequest request) {
      try {
         int userId = Utils.getUserId(request);
         
         if (request.getParameter("sidebarpage") != null) {
            request.getSession().setAttribute(
               "sidebarpage", 
               Utils.idVal(request.getParameter("sidebarpage"))
            ); 
         }
         
         if ("true".equals(request.getParameter("_allTasks")))
            request.getSession().removeAttribute("searchTaskTemplate");
         
         int page = (request.getSession().getAttribute("sidebarpage") == null) ? 0 : (Integer)request.getSession().getAttribute("sidebarpage");         
         int itemsPerPage = 5; 
         
         IntWrapper records = new IntWrapper(0);         
         
         String order = request.getParameter("sidebarorder");
         String orderBy = request.getParameter("sidebarorderBy");
         
         order = (order == null) ? "N" : order;                
         orderBy = (orderBy == null) ? "DESC" : orderBy;         
         
         Collection<TaskBean> tasksList = null;
         
         TaskBean searchTaskTemplate = 
            (TaskBean)request.getSession().getAttribute("searchTaskTemplate");
         
         RequestManagerLocalObject requestManager = 
            requestManagerHome.create();                           
         
         
         if (searchTaskTemplate != null)
         tasksList = 
            requestManager.searchTasksByExecutor(
              searchTaskTemplate,
              orderBy, 
              order,
              page,
              itemsPerPage,
              records
            );         
         else
         tasksList = 
         requestManager.selectTasksByExecutor(
            userId, 
            order, 
            orderBy,
            page,
            itemsPerPage,
            records
         );
               
         request.setAttribute("tasksList", tasksList);
         
         Utils.pageNavigationToRequest(
            page,          
            records.getValue(), 
            "executorui?_action=dumb&sidebarpage=",
            request,
            "sidebarpaging",
            "sidebarcurrentpage"
         );
                                     
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }     
   }

   
   protected void epilogue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {
         
         this.displayUserName(request);
         this.displaySideBarList(request);
         
      } catch (Exception e) {
         handleException(e, "epilogue");
      }
   }
}